"use client"

import { useState } from "react"
import { Card, Table, Typography, Space, Tag, Input, DatePicker, Button, Select, Row, Col, Tooltip, Badge } from "antd"
import {
  SearchOutlined,
  FilterOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  WarningOutlined,
  ProjectOutlined,
  FileTextOutlined,
  CloudServerOutlined,
  UserOutlined,
} from "@ant-design/icons"
import { useHosts } from "../contexts/HostsContext"
import dayjs from "dayjs"
import type { Log } from "../types"

const { Title, Text } = Typography
const { RangePicker } = DatePicker
const { Option } = Select

const LogsPage = () => {
  const { logs, loading } = useHosts()

  const [searchText, setSearchText] = useState("")
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null] | null>(null)
  const [actionType, setActionType] = useState<string | undefined>(undefined)
  const [targetType, setTargetType] = useState<string | undefined>(undefined)

  // Filter logs based on search and filters
  const filteredLogs = logs.filter((log) => {
    const matchesSearch =
      !searchText ||
      log.targetName.toLowerCase().includes(searchText.toLowerCase()) ||
      log.userName.toLowerCase().includes(searchText.toLowerCase()) ||
      log.details.toLowerCase().includes(searchText.toLowerCase())

    const matchesDateRange =
      !dateRange ||
      !dateRange[0] ||
      !dateRange[1] ||
      (dayjs(log.timestamp).isAfter(dateRange[0]) && dayjs(log.timestamp).isBefore(dateRange[1]))

    const matchesAction = !actionType || log.action === actionType
    const matchesTargetType = !targetType || log.targetType === targetType

    return matchesSearch && matchesDateRange && matchesAction && matchesTargetType
  })

  const handleReset = () => {
    setSearchText("")
    setDateRange(null)
    setActionType(undefined)
    setTargetType(undefined)
  }

  const getActionTag = (action: string) => {
    switch (action) {
      case "create":
        return (
          <Tag icon={<CheckCircleOutlined />} color="success">
            创建
          </Tag>
        )
      case "update":
        return (
          <Tag icon={<WarningOutlined />} color="warning">
            更新
          </Tag>
        )
      case "delete":
        return (
          <Tag icon={<CloseCircleOutlined />} color="error">
            删除
          </Tag>
        )
      default:
        return (
          <Tag icon={<CheckCircleOutlined />} color="default">
            {action}
          </Tag>
        )
    }
  }

  const getTargetTypeTag = (targetType: string) => {
    switch (targetType) {
      case "project":
        return (
          <Tag icon={<ProjectOutlined />} color="blue">
            项目
          </Tag>
        )
      case "module":
        return (
          <Tag icon={<FileTextOutlined />} color="purple">
            模块
          </Tag>
        )
      case "hostsBlock":
        return (
          <Tag icon={<CloudServerOutlined />} color="cyan">
            Hosts 配置
          </Tag>
        )
      default:
        return <Tag color="default">{targetType}</Tag>
    }
  }

  const columns = [
    {
      title: "操作类型",
      dataIndex: "action",
      key: "action",
      render: (action: string) => getActionTag(action),
      filters: [
        { text: "创建", value: "create" },
        { text: "更新", value: "update" },
        { text: "删除", value: "delete" },
      ],
      onFilter: (value: string, record: Log) => record.action === value,
    },
    {
      title: "目标类型",
      dataIndex: "targetType",
      key: "targetType",
      render: (targetType: string) => getTargetTypeTag(targetType),
      filters: [
        { text: "项目", value: "project" },
        { text: "模块", value: "module" },
        { text: "Hosts 配置", value: "hostsBlock" },
      ],
      onFilter: (value: string, record: Log) => record.targetType === value,
    },
    {
      title: "目标名称",
      dataIndex: "targetName",
      key: "targetName",
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: "操作详情",
      dataIndex: "details",
      key: "details",
      render: (text: string) => <Text>{text}</Text>,
    },
    {
      title: "操作人",
      dataIndex: "userName",
      key: "userName",
      render: (text: string) => (
        <Space>
          <Badge count={<UserOutlined style={{ color: "#1677ff" }} />} offset={[0, 0]}>
            <Text>{text}</Text>
          </Badge>
        </Space>
      ),
    },
    {
      title: "操作时间",
      dataIndex: "timestamp",
      key: "timestamp",
      render: (text: string) => (
        <Tooltip title={dayjs(text).format("YYYY-MM-DD HH:mm:ss")}>{dayjs(text).fromNow()}</Tooltip>
      ),
      sorter: (a: Log, b: Log) => dayjs(a.timestamp).unix() - dayjs(b.timestamp).unix(),
      defaultSortOrder: "descend",
    },
  ]

  return (
    <div className="fade-in">
      <div className="page-header">
        <Title level={2} className="page-title">
          操作日志
        </Title>
      </div>

      <Card className="filter-container" bordered={false}>
        <Row gutter={[16, 16]} align="middle">
          <Col xs={24} sm={24} md={6}>
            <Input
              placeholder="搜索日志..."
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              allowClear
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Select
              placeholder="操作类型"
              style={{ width: "100%" }}
              allowClear
              value={actionType}
              onChange={setActionType}
            >
              <Option value="create">创建</Option>
              <Option value="update">更新</Option>
              <Option value="delete">删除</Option>
            </Select>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Select
              placeholder="目标类型"
              style={{ width: "100%" }}
              allowClear
              value={targetType}
              onChange={setTargetType}
            >
              <Option value="project">项目</Option>
              <Option value="module">模块</Option>
              <Option value="hostsBlock">Hosts 配置</Option>
            </Select>
          </Col>
          <Col xs={24} sm={24} md={6}>
            <Space>
              <Button icon={<FilterOutlined />} onClick={handleReset}>
                重置筛选
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      <Card className="custom-table log-table" bordered={false} style={{ marginTop: 24 }}>
        <Table
          columns={columns}
          dataSource={filteredLogs}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>
    </div>
  )
}

export default LogsPage
